#include <windows.h>
#include <wininet.h>
#include <intrin.h>

#define HOSTNAME TEXT("www.baidu.com")
#define URLPATH TEXT("/")

typedef struct
{
    HANDLE hEvent;
    HINTERNET hRequest;
} Data;

void CALLBACK InternetStatusCallback(HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength);

void mainCRTStartup()
{
    Data data = {CreateEvent(NULL, FALSE, FALSE, NULL), 0};
    HINTERNET hOpen = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, INTERNET_FLAG_ASYNC);
    InternetSetStatusCallback(hOpen, InternetStatusCallback);
    HINTERNET hConnect = InternetConnect(hOpen, HOSTNAME, INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)&data);
    data.hRequest = HttpOpenRequest(hConnect, NULL, URLPATH, NULL, NULL, NULL, INTERNET_FLAG_SECURE, (DWORD_PTR)&data);
    HttpSendRequest(data.hRequest, NULL, 0, NULL, 0);
    WaitForSingleObject(data.hEvent, INFINITE);
    InternetCloseHandle(data.hRequest);
    InternetCloseHandle(hConnect);
    InternetCloseHandle(hOpen);
    CloseHandle(data.hEvent);
    ExitProcess(0);
}

void CALLBACK InternetStatusCallback(HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength)
{
    UNREFERENCED_PARAMETER(hInternet);
    UNREFERENCED_PARAMETER(dwInternetStatus);
    UNREFERENCED_PARAMETER(lpvStatusInformation);
    UNREFERENCED_PARAMETER(dwStatusInformationLength);

    if (dwInternetStatus != INTERNET_STATUS_REQUEST_COMPLETE)
        return;

    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD dwRead = 0;
    Data *pData = (Data *)dwContext;
    do
    {
        char buf[1024];
        InternetReadFile(pData->hRequest, buf, sizeof buf, &dwRead);
        WriteConsoleA(hStdOut, buf, dwRead, NULL, NULL);
    } while (dwRead > 0);
    SetEvent(pData->hEvent);
}